package com.example.javagd.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @program: springdemo
 * @description:
 * @author: hzy
 * @create: 2020-06-14 11:48
 **/
@Component
public class JWTUtils {
    private  final long EXPIRE_TIME= 7*24*60*60*1000;
    private  final String TOKEN_SECRET="token123";  //密钥盐

    public String CreateToken(String key){
        Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        return JWT.create()
                .withIssuer("auth0")
                .withClaim("key", key)
                .withExpiresAt(expiresAt)
                .sign(Algorithm.HMAC256(TOKEN_SECRET));
    }

    public boolean Verify(String token){
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
            if (jwt.getExpiresAt().after(new Date())){
                return true;
            }
            return false;
        } catch (Exception e){
            return false;
        }

    }
}
